package cn.fanqinghong.ymcc.mq.consumer;

import cn.fanqinghong.ymcc.constants.MessageConstants;
import cn.fanqinghong.ymcc.domain.MessageSms;
import cn.fanqinghong.ymcc.dto.SmsMessageDto;
import cn.fanqinghong.ymcc.exception.GlobalException;
import cn.fanqinghong.ymcc.service.IMessageSmsService;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * FAN
 * 短信发送的消费者
 * 2022/7/25  14:49
 */
@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = MessageConstants.SMS_CONSUMER_GROUP,
        topic = MessageConstants.SMS_TOPIC,
        selectorExpression = MessageConstants.SMS_TAGES
)
public class MessageSMSConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    @Transactional
    public void onMessage(MessageExt message) {
        try {
            byte[] body = message.getBody();
            if (body == null || body.length ==0 ){
                return;
            }
            String jsonStr = new String(message.getBody(), CharsetUtil.UTF_8);
            //把接收到的消息转为MediaFile格式
            SmsMessageDto smsMessageDto = JSONObject.parseObject(jsonStr, SmsMessageDto.class);

            //保存数据到数据库
            SaveMessageSms(smsMessageDto);
            //调用发送接口发送短信

            log.info("发送消息成功"+ smsMessageDto.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("短信发送失败");
        }


    }

    /**
     * 保存数据到数据库
     * @param smsMessageDto
     */
    private void SaveMessageSms(SmsMessageDto smsMessageDto) {
        Date date = new Date();
       smsMessageDto.getDtos().forEach(user ->{
           MessageSms messageSms = new MessageSms();
           BeanUtils.copyProperties(smsMessageDto,messageSms);
           messageSms.setUserId(user.getId());
           messageSms.setMobile(user.getPhone());
           messageSms.setSendTime(date);
           //保存数据
           messageSmsService.insert(messageSms);
       });

    }
}
